<template>
  <div class="owner-list-container">
    <el-card class="owner-card">
      <template #header>
        <div class="card-header">
          <div class="breadcrumb">
            <el-breadcrumb separator="/">
              <el-breadcrumb-item :to="{ path: '/region' }">区域管理</el-breadcrumb-item>
              <el-breadcrumb-item>业主管理</el-breadcrumb-item>
            </el-breadcrumb>
          </div>
          <div class="header-buttons">
            <el-button type="primary" @click="handleAdd">
              <el-icon><Plus /></el-icon>
              新增业主
            </el-button>
            <el-button type="danger" @click="handleBatchDelete" :disabled="selectedIds.length === 0">
              <el-icon><Delete /></el-icon>
              批量删除
            </el-button>
          </div>
        </div>
      </template>
      
      <!-- 统计卡片 -->
      <el-row :gutter="16" class="stats-row">
        <el-col :span="6">
          <el-card class="stats-card">
            <div class="stats-content">
              <div class="stats-icon primary">
                <el-icon><User /></el-icon>
              </div>
              <div class="stats-info">
                <div class="stats-number">{{ statistics.totalCount }}</div>
                <div class="stats-label">总业主数</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stats-card">
            <div class="stats-content">
              <div class="stats-icon success">
                <el-icon><House /></el-icon>
              </div>
              <div class="stats-info">
                <div class="stats-number">{{ statistics.activeCount }}</div>
                <div class="stats-label">活跃业主</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stats-card">
            <div class="stats-content">
              <div class="stats-icon warning">
                <el-icon><Key /></el-icon>
              </div>
              <div class="stats-info">
                <div class="stats-number">{{ statistics.propertyCount }}</div>
                <div class="stats-label">关联房产</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stats-card">
            <div class="stats-content">
              <div class="stats-icon info">
                <el-icon><Document /></el-icon>
              </div>
              <div class="stats-info">
                <div class="stats-number">{{ statistics.certificateCount }}</div>
                <div class="stats-label">房产证数</div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
      
      <!-- 搜索区域 -->
      <div class="search-area">
        <el-form :model="searchForm" inline>
          <el-form-item label="业主姓名">
            <el-input
              v-model="searchForm.ownerName"
              placeholder="请输入业主姓名"
              clearable
              style="width: 200px"
            />
          </el-form-item>
          <el-form-item label="身份证号">
            <el-input
              v-model="searchForm.idCard"
              placeholder="请输入身份证号"
              clearable
              style="width: 200px"
            />
          </el-form-item>
          <el-form-item label="联系电话">
            <el-input
              v-model="searchForm.phone"
              placeholder="请输入联系电话"
              clearable
              style="width: 200px"
            />
          </el-form-item>
          <el-form-item label="邮箱地址">
            <el-input
              v-model="searchForm.email"
              placeholder="请输入邮箱地址"
              clearable
              style="width: 200px"
            />
          </el-form-item>
          <el-form-item label="性别">
            <el-select v-model="searchForm.gender" placeholder="请选择性别" clearable style="width: 120px">
              <el-option label="男" :value="1" />
              <el-option label="女" :value="2" />
              <el-option label="未知" :value="0" />
            </el-select>
          </el-form-item>
          <el-form-item label="职业">
            <el-input
              v-model="searchForm.occupation"
              placeholder="请输入职业"
              clearable
              style="width: 150px"
            />
          </el-form-item>
          <el-form-item label="工作单位">
            <el-input
              v-model="searchForm.company"
              placeholder="请输入工作单位"
              clearable
              style="width: 200px"
            />
          </el-form-item>
          <el-form-item label="关联状态">
            <el-select v-model="searchForm.associationStatus" placeholder="请选择关联状态" clearable style="width: 150px">
              <el-option label="已关联房户" :value="1" />
              <el-option label="未关联房户" :value="0" />
            </el-select>
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="searchForm.status" placeholder="请选择状态" clearable style="width: 150px">
              <el-option label="启用" :value="1" />
              <el-option label="禁用" :value="0" />
            </el-select>
          </el-form-item>
          <el-form-item label="关键词">
            <el-input
              v-model="searchForm.keyword"
              placeholder="请输入关键词搜索"
              clearable
              style="width: 200px"
            />
          </el-form-item>
          <el-form-item label="出生日期">
            <el-date-picker
              v-model="searchForm.birthDateStart"
              type="date"
              placeholder="开始日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              style="width: 150px"
            />
            <span style="margin: 0 8px">至</span>
            <el-date-picker
              v-model="searchForm.birthDateEnd"
              type="date"
              placeholder="结束日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              style="width: 150px"
            />
          </el-form-item>
          <el-form-item label="创建时间">
            <el-date-picker
              v-model="searchForm.createTimeStart"
              type="datetime"
              placeholder="开始时间"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
              style="width: 180px"
            />
            <span style="margin: 0 8px">至</span>
            <el-date-picker
              v-model="searchForm.createTimeEnd"
              type="datetime"
              placeholder="结束时间"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
              style="width: 180px"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">
              <el-icon><Search /></el-icon>
              查询
            </el-button>
            <el-button @click="handleReset">
              <el-icon><Refresh /></el-icon>
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>
      
      <!-- 数据表格 -->
      <el-table
        :data="ownerList"
        v-loading="loading"
        @selection-change="handleSelectionChange"
        style="width: 100%"
        row-key="id"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="ownerName" label="业主姓名" width="120" />
        <el-table-column prop="idCard" label="身份证号" width="180" />
        <el-table-column prop="phone" label="联系电话" width="130" />
        <el-table-column prop="email" label="邮箱地址" width="180" />
        <el-table-column prop="gender" label="性别" width="80">
          <template #default="{ row }">
            <el-tag :type="row.gender === 1 ? 'primary' : row.gender === 2 ? 'success' : 'info'">
              {{ row.gender === 1 ? '男' : row.gender === 2 ? '女' : '未知' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="关联状态" width="120">
          <template #default="{ row }">
            <div class="association-info">
              <el-tag 
                :type="row.associationStatus === 1 ? 'success' : 'warning'"
                @click="handleViewHousehold(row)"
              >
                {{ row.associationStatusText || (row.associationStatus === 1 ? '已关联' : '未关联') }}
              </el-tag>
              <el-button 
                v-if="row.associationStatus === 0" 
                type="text" 
                size="small" 
                @click="handleAssociateHousehold(row)"
                style="margin-left: 5px;"
              >
                关联房户
              </el-button>
              <el-button 
                v-else-if="row.householdCount > 0" 
                type="text" 
                size="small" 
                @click="handleViewHousehold(row)"
                style="margin-left: 5px;"
              >
                查看
              </el-button>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="关联房户" width="120">
          <template #default="{ row }">
            <div class="household-info">
              <el-tag :type="row.householdCount > 0 ? 'success' : 'info'" @click="handleViewHousehold(row)">
                {{ row.householdCount || 0 }}套
              </el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="birthDate" label="出生日期" width="120" />
        <el-table-column prop="occupation" label="职业" width="120" />
        <el-table-column prop="status" label="状态" width="80">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'danger'">
              {{ row.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="160" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleEdit(row)">
              <el-icon><Edit /></el-icon>
              编辑
            </el-button>
            <el-button type="success" size="small" @click="handleViewHousehold(row)">
              <el-icon><House /></el-icon>
              房户
            </el-button>
            <el-button type="danger" size="small" @click="handleDelete(row)">
              <el-icon><Delete /></el-icon>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页控件 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    
    <!-- 业主表单对话框 -->
    <OwnerForm
      v-model:visible="formVisible"
      :owner-data="currentOwner"
      @success="handleFormSuccess"
    />
    
    <!-- 新增业主对话框 -->
    <OwnerAddForm
      v-model:visible="addFormVisible"
      @success="handleAddFormSuccess"
    />
    
    <!-- 业主房户关联对话框 -->
    <OwnerHousehold
      v-model:visible="householdVisible"
      :owner-data="currentOwner"
      @success="handleHouseholdSuccess"
    />
    
    <!-- 关联房户对话框 -->
    <AssociateHouseholdDialog
      v-model:visible="associateHouseholdVisible"
      :owner-data="currentOwner"
      @success="handleHouseholdSuccess"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Delete, Search, Refresh, Edit, User, House, Key, Document } from '@element-plus/icons-vue'
import OwnerForm from './components/OwnerForm.vue'
import OwnerAddForm from './components/OwnerAddForm.vue'
import OwnerHousehold from './components/OwnerHousehold.vue'
import AssociateHouseholdDialog from './components/AssociateHouseholdDialog.vue'
import { ownerApi, type OwnerData, type OwnerQueryDTO, type OwnerStatistics } from '@/api/owner'
import { ownerHouseholdApi } from '@/api/ownerHousehold'

// 响应式数据
const loading = ref(false)
const formVisible = ref(false)
const addFormVisible = ref(false)
const householdVisible = ref(false)
const associateHouseholdVisible = ref(false)
const currentOwner = ref<any>(null)
const selectedIds = ref<number[]>([])

// 搜索表单 - 遵循Element Plus组件编码规范，使用undefined而不是null
const searchForm = reactive({
  ownerName: '',
  idCard: '',
  phone: '',
  email: '',
  gender: undefined as number | undefined,
  occupation: '',
  company: '',
  associationStatus: undefined as number | undefined,
  status: undefined as number | undefined,
  keyword: '',
  birthDateStart: '',
  birthDateEnd: '',
  createTimeStart: '',
  createTimeEnd: ''
})

// 分页信息
const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 统计数据
const statistics = reactive({
  totalCount: 0,
  activeCount: 0,
  propertyCount: 0,
  certificateCount: 0
})

// 业主列表数据
const ownerList = ref<OwnerData[]>([])

// 生命周期
onMounted(() => {
  loadOwnerList()
  loadStatistics()
})

// 加载业主列表
const loadOwnerList = async () => {
  try {
    loading.value = true
    const queryParams: OwnerQueryDTO = {
      ...searchForm,
      current: pagination.current,
      size: pagination.size
    }
    
    // 使用新的API接口，包含关联状态信息
    const response = await ownerApi.getOwnerListWithAssociation(queryParams)
    if (response.code === 200 && response.data) {
      ownerList.value = response.data.records || []
      pagination.total = response.data.total || 0
    } else {
      ElMessage.error(response.message || '加载业主列表失败')
    }
  } catch (error) {
    console.error('加载业主列表失败:', error)
    ElMessage.error('加载业主列表失败')
  } finally {
    loading.value = false
  }
}

// 加载统计数据
const loadStatistics = async () => {
  try {
    const response = await ownerApi.getOwnerStatistics()
    if (response.code === 200 && response.data) {
      Object.assign(statistics, response.data)
    }
  } catch (error) {
    console.error('加载统计数据失败:', error)
    // 统计数据加载失败不影响主功能
  }
}



// 搜索处理
const handleSearch = () => {
  pagination.current = 1
  loadOwnerList()
}

// 重置搜索
const handleReset = () => {
  Object.assign(searchForm, {
    ownerName: '',
    idCard: '',
    phone: '',
    email: '',
    gender: undefined,
    occupation: '',
    company: '',
    associationStatus: undefined,
    status: undefined,
    keyword: '',
    birthDateStart: '',
    birthDateEnd: '',
    createTimeStart: '',
    createTimeEnd: ''
  })
  pagination.current = 1
  loadOwnerList()
}

// 选择变化处理
const handleSelectionChange = (selection: any[]) => {
  selectedIds.value = selection.map(item => item.id)
}

// 新增业主
const handleAdd = () => {
  currentOwner.value = null
  addFormVisible.value = true
}

// 编辑业主
const handleEdit = async (row: any) => {
  try {
    loading.value = true
    // 使用getOwnerEditData获取不脱敏的编辑数据
    const response = await ownerApi.getOwnerEditData(row.id)
    if (response.code === 200 && response.data) {
      currentOwner.value = response.data
      formVisible.value = true
    } else {
      ElMessage.error(response.message || '获取业主详情失败')
    }
  } catch (error) {
    console.error('获取业主详情失败:', error)
    ElMessage.error('获取业主详情失败')
  } finally {
    loading.value = false
  }
}

// 查看房户关联
const handleViewHousehold = (row: any) => {
  // 直接打开对话框，对话框内部会加载房户数据
  currentOwner.value = { ...row }
  householdVisible.value = true
}


// 删除业主
const handleDelete = async (row: any) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除业主"${row.ownerName}"吗？${row.householdCount > 0 ? `该业主还有${row.householdCount}套关联房产，删除后将同时解除所有关联关系。` : ''}`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const response = await ownerApi.deleteOwner(row.id)
    if (response.code === 200) {
      ElMessage.success('删除成功')
      loadOwnerList()
      loadStatistics()
    } else {
      ElMessage.error(response.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除业主失败:', error)
      ElMessage.error('删除业主失败')
    }
  }
}

// 批量删除
const handleBatchDelete = async () => {
  if (selectedIds.value.length === 0) {
    ElMessage.warning('请选择要删除的业主')
    return
  }
  
  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedIds.value.length} 个业主吗？`,
      '确认批量删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const response = await ownerApi.batchDeleteOwners(selectedIds.value)
    if (response.code === 200) {
      selectedIds.value = []
      ElMessage.success('批量删除成功')
      loadOwnerList()
      loadStatistics()
    } else {
      ElMessage.error(response.message || '批量删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量删除业主失败:', error)
      ElMessage.error('批量删除业主失败')
    }
  }
}



// 表单成功回调
const handleFormSuccess = () => {
  formVisible.value = false
  ElMessage.success('操作成功')
  // 重新加载数据
  loadOwnerList()
  loadStatistics()
}

// 新增业主成功回调
const handleAddFormSuccess = () => {
  addFormVisible.value = false
  ElMessage.success('新增业主成功')
  // 重新加载数据
  loadOwnerList()
  loadStatistics()
}

// 关联房户
const handleAssociateHousehold = (row: OwnerData) => {
  currentOwner.value = row
  associateHouseholdVisible.value = true
}

// 房户关联成功回调
const handleHouseholdSuccess = () => {
  householdVisible.value = false
  ElMessage.success('房户关联操作成功')
  // 重新加载数据
  loadOwnerList()
  loadStatistics()
}

// 分页大小变化
const handleSizeChange = (size: number) => {
  pagination.size = size
  pagination.current = 1
  loadOwnerList()
}

// 当前页变化
const handleCurrentChange = (current: number) => {
  pagination.current = current
  loadOwnerList()
}


</script>

<style scoped>
.owner-list-container {
  padding: 20px;
}

.owner-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-buttons {
  display: flex;
  gap: 10px;
}

.stats-row {
  margin-bottom: 20px;
}

.stats-card {
  border: none;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.stats-content {
  display: flex;
  align-items: center;
  padding: 10px;
}

.stats-icon {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 15px;
  font-size: 24px;
  color: white;
}

.stats-icon.primary {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.stats-icon.success {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}

.stats-icon.warning {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
}

.stats-icon.info {
  background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
}

.stats-info {
  flex: 1;
}

.stats-number {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 5px;
}

.stats-label {
  font-size: 14px;
  color: #909399;
}

.search-area {
  margin-bottom: 20px;
  padding: 20px;
  background: #f5f7fa;
  border-radius: 8px;
}

.household-info {
  display: flex;
  align-items: center;
}


.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}
</style>
